package com.wlcb.jpower.chat.server.handler;

import cn.hutool.core.util.URLUtil;
import com.wlcb.jpower.chat.service.customer.CustomerSettingService;
import com.wlcb.jpower.constant.ChatConfigConstant;
import com.wlcb.jpower.feign.UserClient;
import com.wlcb.jpower.im.cache.Session;
import com.wlcb.jpower.im.cache.SessionCache;
import com.wlcb.jpower.module.common.auth.UserInfo;
import com.wlcb.jpower.module.common.deploy.props.JpowerProperties;
import com.wlcb.jpower.module.common.utils.*;
import com.wlcb.jpower.module.common.utils.constants.AppConstant;
import com.wlcb.jpower.utils.UriUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;

import java.nio.charset.Charset;

/**
 * 安全处理
 */
@Slf4j
public class ChatInterceptHandler extends ChannelInboundHandlerAdapter {

    private static final UserClient userClient;

    private static final JpowerProperties jpowerProperties;

    static {
        jpowerProperties = SpringUtil.getBean(JpowerProperties.class);
        userClient = SpringUtil.getBean(UserClient.class);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;
            String uri = URLUtil.decode(fullHttpRequest.uri(), Charset.defaultCharset());
            String auth = UriUtils.getAuth(uri);
            UserInfo userInfo = SecureUtil.getUser(JwtUtil.parseJWT(auth));
            if (Fc.notNull(userInfo)) {
                fullHttpRequest.setUri(ChatConfigConstant.ChatAppConstant.CHAT);
                ctx.fireUserEventTriggered(userInfo);
                Session session = BeanUtil.copyProperties(userInfo, Session.class);
                if (AppConstant.PROD_CODE.equals(jpowerProperties.getEnv()) && userClient.queryUserByLoginId(userInfo.getLoginId(), userInfo.getTenantCode()).getData() == null) {
                    ctx.close();
                }
                if (SessionCache.isSession(session.getLoginId())) {
                    ctx.close();
                } else {
                    session.setChannel(ctx.channel());
                    session.setBindTime(System.currentTimeMillis());
                    if (SessionCache.addSession(session)) {
                        generateSettings(session.getLoginId());
                    } else {
                        ctx.close();
                    }
                    super.channelRead(ctx, msg);
                }
            } else {
                String wxcid = UriUtils.getWxcid(uri);
                if (Fc.isNotBlank(wxcid)) {
                    // TODO: 2022/2/24 0024 之前这里固定写死了租户是000001，现在改成获取登录租户(SecureUtil.getTenantCode())，但不知道好使不好使，没有测试
                    if (AppConstant.PROD_CODE.equals(jpowerProperties.getEnv()) && userClient.queryUserByLoginId(wxcid, SecureUtil.getTenantCode()).getData() == null) {
                        ctx.close();
                    }
                    if (SessionCache.isSession(wxcid)) {
                        ctx.close();
                    }
                    fullHttpRequest.setUri(ChatConfigConstant.ChatAppConstant.CHAT);
                    UserInfo wxuser = new UserInfo();
                    wxuser.setLoginId(wxcid);
                    wxuser.setUserType(ChatConfigConstant.UserType.CUSTOMER);
                    Session session = BeanUtil.copyProperties(wxuser, Session.class);
                    session.setBindTime(System.currentTimeMillis());
                    session.setChannel(ctx.channel());

                    if (SessionCache.addSession(session)) {
                        generateSettings(session.getLoginId());
                    } else {
                        ctx.close();
                    }
                    super.channelRead(ctx, msg);
                }
            }
        } else if (msg instanceof TextWebSocketFrame) {
            ctx.fireChannelRead(msg);
        }
    }

    /**
     * 连接成功 生成客服默认配置信息并保存
     *
     * @param cid
     */
    private void generateSettings(String cid) {
        CustomerSettingService settingService = SpringUtil.getBean(CustomerSettingService.class);
        settingService.save(cid);
    }
}
